﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DeskDict.Schema;
using System.IO;
using DeskDict.schema;

namespace DeskDict.Provider
{
    public class XmlDictProvider : IDictProvider
    {
        private string WordXmlPath = @"data/word.xml";
        private Dictionary<string, wordbookItem> dict;

        public XmlDictProvider()
        {
            Initialize();
        }

        private void Initialize()
        {
            try
            {
                string xml = File.ReadAllText(WordXmlPath);
                wordbook book = XmlParser.Deserialize<wordbook>(xml);
                dict = book.item.ToDictionary<wordbookItem, string>(item => item.word);
            }
            catch (Exception e)
            {
                // write log
            }
        }

        public WordDetail Translate(string word)
        {
            if (dict.ContainsKey(word))
            {
                return Translate(dict[word]);
            }
            return null;
        }

        public static WordDetail Translate(wordbookItem item)
        {
            return new WordDetail
            {
                Word = item.word,
                Phonetic = item.phonetic,
                Trans = item.trans,
                Sample = null,
                Tag = item.tags.ToString()
            };
        }


        public List<string> GetWordList()
        {
            if (dict != null)
            {
                return dict.Keys.ToList();
            }
            else
            {
                return new List<string>();
            }
        }
    }
}
